package com.ktgj.service.common.ygcd.domain.util;

import org.apache.commons.codec.digest.DigestUtils;

import java.io.*;
import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * @author wyj
 * @create 2021-10-21 11:38
 */
public class Utils {
    //测试环境
    public static int companyid=41;
    public static String secretKey="12345678";
    //服务地址
    public static String CDServiceUri="http://beta.car.jryghq.com/";


    //正式环境
    /*public static int companyid=41;
    public static String secretKey="f9brwaif";
    public static String CDServiceUri="http://api.car.jryghq.com/";*/


    /**
     * 请求对象加签名
     * @param request
     * @return
     */
    public static String getSign(Object request){
        Map<String, Object> objectToMap = getObjectToMap(request);
        //objectToMap = sortMapByKey(objectToMap);

        String result = "";
        List<String> stringList = new LinkedList<>();
        if(objectToMap!=null){
            Iterator<String> it = objectToMap.keySet().iterator();
            while (it.hasNext()) {
                String key = it.next();
                Object value = objectToMap.get(key);
                if(!"sign".toLowerCase().equals(value)){
                    if("".equals(value) || value ==null){
                        stringList.add(key);

                    }else{
                        stringList.add(key+value.toString());
                    }
                }
            }
        }

        //排序
        Collections.sort(stringList);
        StringBuffer buffer = null;
        if(stringList.size()>0){
            buffer = new StringBuffer();
            for (String str : stringList) {
                buffer.append(str);
            }
        }


        String encodeStr = buffer.toString() + secretKey;

        String md5 = encrypt(encodeStr).toUpperCase();

        return md5;

    }

    public static String encrypt(String dataStr) {
        return DigestUtils.md5Hex(dataStr.getBytes(StandardCharsets.UTF_8));
    }

    /**
     * 排序map
     * @param map
     * @return
     */
    public static Map<String,Object> sortMapByKey(Map<String,Object> map){
        if(map == null || map.isEmpty()){
            return null;
        }
        Map<String,Object> sotMap = new TreeMap<>(new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return ((String)o1).compareTo((String)o2);
            }
        });
        sotMap.putAll(map);
        return sotMap;
    }

    /**
     * object转map
     * @param obj
     * @return
     */
    public static Map<String,Object> getObjectToMap(Object obj){
        TreeMap<String,Object> map = new TreeMap<>();
        try {
            Class<?> clazz =  obj.getClass();
            for (Field field : clazz.getDeclaredFields()) {
                String fileName = field.getName();
                Object value = field.get(obj);
                if (value == null){
                    value = "";
                }
                map.put(fileName,value);
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return map;
    }

    public static String postJson(String ur, String strJson) throws IOException {
        URL url = new URL(ur);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.addRequestProperty("Accept", "application/json");
        conn.addRequestProperty("Content-Type", "application/json;charset=utf-8");
        conn.setRequestMethod("POST");

        conn.setUseCaches(false);
        conn.setInstanceFollowRedirects(true);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.connect();

        OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
        out.write(strJson);
        out.flush();

        InputStream is = conn.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        StringBuffer sbf = new StringBuffer();
        String temp = null;
        // 循环遍历一行一行读取数据
        while ((temp = br.readLine()) != null) {
            sbf.append(temp);
        }

        br.close();
        return sbf.toString();
    }

}
